package com.yz.book.controller;


import com.yz.book.entity.Address;
import com.yz.book.entity.User;
import com.yz.book.service.AddressService;
import com.yz.book.service.UserService;
import com.yz.book.utils.CookieUtils;
import com.yz.book.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ste
 * @since 2023-02-04 03:37:36
 */
@Controller
@RequestMapping("/address")
public class AddressController {


    @Autowired
    AddressService addressService;

    @Autowired
    UserService userService;


    private User getCurrentUser(HttpServletRequest request){
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String currentUserAccount = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        User currentUser = userService.getUserByUsername(currentUserAccount);

        return currentUser;
    }

    @GetMapping("all")
    @ResponseBody
    public List<Address> all(HttpServletRequest request){

        User currentUser = getCurrentUser(request);

        List<Address> addressList = addressService.getAll(currentUser.getId());

        return addressList;
    }

    @RequestMapping("add")
    @ResponseBody
    public void add(Address address,HttpServletRequest request){

        User currentUser = getCurrentUser(request);

        address.setUserId(currentUser.getId());

        addressService.save(address);

    }



}

